package com.aidex.biz.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.domain.enums.MessageTypeEnum;
import com.aidex.biz.service.CustomerDongtaiService;
import com.aidex.biz.service.MessageInfoService;
import com.aidex.biz.service.XiezuService;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sign.Md5Utils;
import com.aidex.common.utils.sql.SqlUtil;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.service.ISysUserService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.entity.SysDept;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.framework.cache.DeptUtils;
import com.aidex.framework.cache.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.biz.mapper.CustomerXiezuMapper;
import com.aidex.biz.service.CustomerXiezuService;
import org.springframework.transaction.annotation.Transactional;
import com.aidex.common.utils.NumberUtils;

/**
 * 客户协助Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-11-29
 */
@Service
@Transactional(readOnly = true)
public class CustomerXiezuServiceImpl extends BaseServiceImpl<CustomerXiezuMapper, CustomerXiezu> implements CustomerXiezuService {
    private static final Logger logger = LoggerFactory.getLogger(CustomerXiezuServiceImpl.class);
    @Autowired
    private MessageInfoService messageInfoService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private XiezuService xiezuService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private CustomerShadowInfoServiceImpl customerShadowInfoService;

    /**
     * 获取单条数据
     *
     * @param customerXiezu 客户协助
     * @return 客户协助
     */
    @Override
    public CustomerXiezu get(CustomerXiezu customerXiezu) {
        CustomerXiezu dto = super.get(customerXiezu);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 客户协助id
     * @return 客户协助
     */
    @Override
    public CustomerXiezu get(String id) {
        CustomerXiezu dto = super.get(id);
        return dto;
    }


    /**
     * 查询客户协助列表
     *
     * @param customerXiezu 客户协助
     * @return 客户协助
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<CustomerXiezu> findList(CustomerXiezu customerXiezu) {
        return super.findList(customerXiezu);
    }

    /**
     * 分页查询客户协助列表
     *
     * @param customerXiezu 客户协助
     * @return 客户协助
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<CustomerXiezu> findPage(CustomerXiezu customerXiezu) {
        return super.findPage(customerXiezu);
    }

    /**
     * 保存客户协助
     *
     * @param customerXiezu
     * @return 结果
     */
    @Override
    public boolean save(CustomerXiezu customerXiezu) {
        return super.save(customerXiezu);
    }


    /**
     * 删除客户协助信息
     *
     * @param customerXiezu
     * @return 结果
     */
    @Override
    public boolean remove(CustomerXiezu customerXiezu) {
        return super.remove(customerXiezu);
    }

    /**
     * 批量删除客户协助
     *
     * @param ids 需要删除的客户协助ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteCustomerXiezuByIds(String[] ids) {
        return mapper.deleteCustomerXiezuByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param customerXiezu 客户协助
     * @return 结果
     */
    @Override
    public int findMaxSort(CustomerXiezu customerXiezu) {
        return NumberUtils.nextOrder(mapper.findMaxSort(customerXiezu));
    }

    @Override
    public PageInfo<CustomerXiezu> findMyXieZuList(CustomerXiezu customerXiezu) {
        PageDomain page = customerXiezu.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(addOtherInfo(mapper.findMyXieZuList(customerXiezu)));


    }


    /***
     * 添加关联表信息
     * @param customerList
     * @return
     */
    private List<CustomerXiezu> addOtherInfo(List<CustomerXiezu> customerList) {
        if (null != customerList && !customerList.isEmpty()) {
            List<PushCustomer> pushCustomerList = mapper.findPushCustomerListByPhones(customerList);
            Map<String, List<PushCustomer>> pushCustomerMap =
                    pushCustomerList.stream().collect(Collectors.groupingBy(PushCustomer::getPhone));
            for (CustomerXiezu cus : customerList) {
                cus.setPushList(pushCustomerMap.get(cus.getPhone()));
            }
            List<String> customerIdList =
                    customerList.stream().map(CustomerXiezu::getCustomerId).collect(Collectors.toList());
            List<CustomerShadowInfo> customerShadowInfoList =
                    customerShadowInfoService.findShadowListByCustomerIds(customerIdList);
            Map<String, List<CustomerShadowInfo>> customerShadowInfoMap =
                    customerShadowInfoList.stream().collect(Collectors.groupingBy(CustomerShadowInfo::getCustomerId));
            for (CustomerXiezu cus : customerList) {
                cus.setShadowList(customerShadowInfoMap.get(cus.getCustomerId()));
            }
        }
        return customerList;
    }


    @Override
    @Transactional(readOnly = false)
    public Integer deleteByCustomerId(CustomerXiezu customerXiezu) {
        return mapper.deleteByCustomerId(customerXiezu);
    }

    /**
     * 协助
     *
     * @param xiezhu
     * @return
     */
    private void xiezhu(CustomerXiezu xiezhu) {

        CustomerXiezu customerXiezu = new CustomerXiezu();
        customerXiezu.setCustomerIds(xiezhu.getCustomerIds());
        customerXiezu.setXiezuUsers(xiezhu.getXiezuUsers());
        customerXiezu.setXiezuUserNames(xiezhu.getXiezuUserNames());
        for (String userId : customerXiezu.getXiezuUsers()) {
            List<CustomerXiezu> customerXiezuList = new ArrayList<>();
            List<Customer> customerList = new ArrayList<>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "xiezuCus");
            jsonObject.put("msg", "您有新同事协助信息");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, userId, jsonObject.toJSONString());
            for (String customerId : customerXiezu.getCustomerIds()) {
                SysUser sysUser = iSysUserService.getUserCache(userId);
                if (null == sysUser) {
                    continue;
                }
                customerXiezu.setCustomerId(customerId);
                customerXiezu.setId(Md5Utils.hash(userId + customerId));
                customerXiezu.setIsNewRecord();
                customerXiezu.setXiezuUserId(userId);
                customerXiezu.preInsert();
                // 每次循环都 new 一个新对象，避免引用重复
                CustomerXiezu newXiezu = new CustomerXiezu();
                // 复制原对象的属性
                BeanUtils.copyProperties(customerXiezu, newXiezu);
                customerXiezuList.add(newXiezu);

                Customer customerOne = new Customer();
                customerOne.setUserId(userId);
                customerOne.setUserName(sysUser.getName());
                customerOne.setDeptId(sysUser.getDeptId());
                customerOne.setDeptName(sysUser.getDeptName());
                customerOne.setId(customerId);
                customerList.add(customerOne);
            }
            // 批量新增
            Integer result = this.insertBatch(customerXiezuList);
            if (result > 0) {
                messageInfoService.sendMsgToUserBatch(customerList, MessageTypeEnum.XZKH, jsonObject.getString("msg"));
            }
        }

        String userIds = String.join(",", customerXiezu.getXiezuUsers());
        String userNames = String.join(",", customerXiezu.getXiezuUserNames());
        // 批量新增动态
        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setType(DongTaiTypeEnum.SHADOW.getStatus());
        ;
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-添加协助客户-" + userNames);
        customerDongtai.preInsert();
        customerDongtaiService.insertBatchByCustomerIds(customerXiezu.getCustomerIds(), customerDongtai);

        // 批量新增协助对象
        Xiezu xiezu = new Xiezu();
        xiezu.setXiezuUserIds(userIds);
        xiezu.setXiezuUserNames(userNames);
        xiezu.preInsert();
        xiezuService.insertBatchByCustomerIds(customerXiezu.getCustomerIds(), xiezu);
    }


    @Override
    @Transactional(readOnly = false)
    public Integer insertBatch(List<CustomerXiezu> list) {
        return mapper.insertBatch(list);
    }


    /**
     * 单个客户协助
     *
     * @param customerXiezu
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public void xiezhuSingle(CustomerXiezu customerXiezu) {
        customerXiezu.setCustomerIds(new String[]{customerXiezu.getCustomerId()});
        this.xiezhu(customerXiezu);
    }


    /**
     * 批量客户协助
     *
     * @param customerXiezu
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public void xiezhuBatch(CustomerXiezu customerXiezu) {
        this.xiezhu(customerXiezu);
    }


}
